/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.odg.dg.xml;

import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;

/**
 *
 * @author yura
 */
public class XmlCharsetUtils {
	private static final String XML_CHARSET_PATTERN = "<\\?xml.*encoding=\"(.*)\".*\\?>";
	private static final String XML_PROLOG = XML_CHARSET_PATTERN + "\\s*";

	public static Charset getXmlEncoding(String xml) {
		Pattern pat = Pattern.compile(XML_CHARSET_PATTERN);
		Matcher mat = pat.matcher(xml);
		if (mat.find() && mat.groupCount() > 0) {
			return Charset.forName(mat.group(1));
		}
		return null;
	}

    public static String getXmlProlog(String xml) {
        Pattern pat = Pattern.compile(XML_PROLOG);
		Matcher mat = pat.matcher(xml);
		if (mat.find() && mat.groupCount() > 0) {
			return mat.group();
		}
		return "";
    }

	public static String getEmptySafeEncoding(String encoding) {
		if (StringUtils.isEmpty(encoding)) {
			return Charset.defaultCharset().name();
		} else {
			return encoding;
		}
	}

}
